package com.laundry.shared.notification

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.util.*

/**
 * 推送通知管理器
 */
class PushNotificationManager(private val context: Context) {
    
    companion object {
        private const val CHANNEL_ORDER = "order_notifications"
        private const val CHANNEL_PROMOTION = "promotion_notifications"
        private const val CHANNEL_SYSTEM = "system_notifications"
        private const val CHANNEL_CHAT = "chat_notifications"
        private const val CHANNEL_PAYMENT = "payment_notifications"
    }
    
    private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    
    init {
        createNotificationChannels()
    }
    
    /**
     * 初始化推送服务
     */
    suspend fun initializePushService(userId: String): Flow<String> = flow {
        try {
            FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val token = task.result
                    // 上传token到服务器
                    uploadTokenToServer(userId, token)
                    emit(token)
                } else {
                    emit("")
                }
            }
        } catch (e: Exception) {
            emit("")
        }
    }
    
    /**
     * 订阅主题
     */
    suspend fun subscribeToTopic(topic: String): Flow<Boolean> = flow {
        try {
            FirebaseMessaging.getInstance().subscribeToTopic(topic)
                .addOnCompleteListener { task ->
                    emit(task.isSuccessful)
                }
        } catch (e: Exception) {
            emit(false)
        }
    }
    
    /**
     * 取消订阅主题
     */
    suspend fun unsubscribeFromTopic(topic: String): Flow<Boolean> = flow {
        try {
            FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
                .addOnCompleteListener { task ->
                    emit(task.isSuccessful)
                }
        } catch (e: Exception) {
            emit(false)
        }
    }
    
    /**
     * 处理接收到的推送消息
     */
    fun handleRemoteMessage(remoteMessage: RemoteMessage) {
        val data = remoteMessage.data
        val notification = remoteMessage.notification
        
        val notificationType = data["type"] ?: "system"
        val title = notification?.title ?: data["title"] ?: "新消息"
        val body = notification?.body ?: data["body"] ?: ""
        val imageUrl = notification?.imageUrl?.toString()
        
        when (notificationType) {
            "order_update" -> showOrderNotification(title, body, data, imageUrl)
            "new_message" -> showChatNotification(title, body, data, imageUrl)
            "payment_result" -> showPaymentNotification(title, body, data, imageUrl)
            "promotion" -> showPromotionNotification(title, body, data, imageUrl)
            "system" -> showSystemNotification(title, body, data, imageUrl)
            else -> showDefaultNotification(title, body, data, imageUrl)
        }
        
        // 保存通知记录
        saveNotificationRecord(remoteMessage)
    }
    
    /**
     * 显示订单通知
     */
    private fun showOrderNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val orderId = data["order_id"] ?: ""
        val intent = createOrderDetailIntent(orderId)
        val pendingIntent = createPendingIntent(intent, orderId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_ORDER)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(body)
            .setStyle(NotificationCompat.BigTextStyle().bigText(body))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .apply {
                if (imageUrl != null) {
                    // 加载并设置大图
                    loadImageAndSetBigPicture(this, imageUrl)
                }
                
                // 添加快捷操作
                when (data["order_status"]) {
                    "pending_confirm" -> {
                        addAction(
                            android.R.drawable.ic_menu_view,
                            "查看详情",
                            pendingIntent
                        )
                    }
                    "completed" -> {
                        val reviewIntent = createReviewIntent(orderId)
                        val reviewPendingIntent = createPendingIntent(reviewIntent, (orderId + "_review").hashCode())
                        addAction(
                            android.R.drawable.ic_menu_edit,
                            "评价",
                            reviewPendingIntent
                        )
                    }
                }
            }
            .build()
        
        notificationManager.notify(orderId.hashCode(), notification)
    }
    
    /**
     * 显示聊天通知
     */
    private fun showChatNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val sessionId = data["session_id"] ?: ""
        val senderId = data["sender_id"] ?: ""
        val intent = createChatIntent(sessionId)
        val pendingIntent = createPendingIntent(intent, sessionId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_CHAT)
            .setSmallIcon(android.R.drawable.ic_dialog_email)
            .setContentTitle(title)
            .setContentText(body)
            .setStyle(NotificationCompat.BigTextStyle().bigText(body))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .apply {
                // 添加快速回复
                val replyIntent = createQuickReplyIntent(sessionId)
                val replyPendingIntent = createPendingIntent(replyIntent, (sessionId + "_reply").hashCode())
                addAction(
                    android.R.drawable.ic_menu_send,
                    "快速回复",
                    replyPendingIntent
                )
            }
            .build()
        
        notificationManager.notify(sessionId.hashCode(), notification)
    }
    
    /**
     * 显示支付通知
     */
    private fun showPaymentNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val paymentId = data["payment_id"] ?: ""
        val orderId = data["order_id"] ?: ""
        val intent = createPaymentResultIntent(paymentId, orderId)
        val pendingIntent = createPendingIntent(intent, paymentId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_PAYMENT)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(body)
            .setStyle(NotificationCompat.BigTextStyle().bigText(body))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .build()
        
        notificationManager.notify(paymentId.hashCode(), notification)
    }
    
    /**
     * 显示促销通知
     */
    private fun showPromotionNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val promotionId = data["promotion_id"] ?: ""
        val intent = createPromotionIntent(promotionId)
        val pendingIntent = createPendingIntent(intent, promotionId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_PROMOTION)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(body)
            .setStyle(NotificationCompat.BigTextStyle().bigText(body))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .apply {
                if (imageUrl != null) {
                    loadImageAndSetBigPicture(this, imageUrl)
                }
            }
            .build()
        
        notificationManager.notify(promotionId.hashCode(), notification)
    }
    
    /**
     * 显示系统通知
     */
    private fun showSystemNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val notificationId = data["notification_id"] ?: UUID.randomUUID().toString()
        val intent = createSystemNotificationIntent(notificationId)
        val pendingIntent = createPendingIntent(intent, notificationId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_SYSTEM)
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setContentTitle(title)
            .setContentText(body)
            .setStyle(NotificationCompat.BigTextStyle().bigText(body))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build()
        
        notificationManager.notify(notificationId.hashCode(), notification)
    }
    
    /**
     * 显示默认通知
     */
    private fun showDefaultNotification(
        title: String,
        body: String,
        data: Map<String, String>,
        imageUrl: String?
    ) {
        val notificationId = UUID.randomUUID().toString()
        val intent = createDefaultIntent()
        val pendingIntent = createPendingIntent(intent, notificationId.hashCode())
        
        val notification = NotificationCompat.Builder(context, CHANNEL_SYSTEM)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()
        
        notificationManager.notify(notificationId.hashCode(), notification)
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channels = listOf(
                NotificationChannel(
                    CHANNEL_ORDER,
                    "订单通知",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    description = "订单状态更新通知"
                    enableVibration(true)
                    enableLights(true)
                },
                NotificationChannel(
                    CHANNEL_CHAT,
                    "聊天消息",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    description = "客服聊天消息通知"
                    enableVibration(true)
                    enableLights(true)
                },
                NotificationChannel(
                    CHANNEL_PAYMENT,
                    "支付通知",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    description = "支付结果通知"
                    enableVibration(true)
                    enableLights(true)
                },
                NotificationChannel(
                    CHANNEL_PROMOTION,
                    "促销活动",
                    NotificationManager.IMPORTANCE_DEFAULT
                ).apply {
                    description = "促销活动和优惠信息"
                },
                NotificationChannel(
                    CHANNEL_SYSTEM,
                    "系统通知",
                    NotificationManager.IMPORTANCE_DEFAULT
                ).apply {
                    description = "系统公告和重要通知"
                }
            )
            
            channels.forEach { channel ->
                notificationManager.createNotificationChannel(channel)
            }
        }
    }
    
    // 私有辅助方法
    private fun createPendingIntent(intent: Intent, requestCode: Int): PendingIntent {
        return PendingIntent.getActivity(
            context,
            requestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
    }
    
    private fun createOrderDetailIntent(orderId: String): Intent {
        return Intent().apply {
            putExtra("order_id", orderId)
            putExtra("action", "view_order_detail")
        }
    }
    
    private fun createReviewIntent(orderId: String): Intent {
        return Intent().apply {
            putExtra("order_id", orderId)
            putExtra("action", "review_order")
        }
    }
    
    private fun createChatIntent(sessionId: String): Intent {
        return Intent().apply {
            putExtra("session_id", sessionId)
            putExtra("action", "open_chat")
        }
    }
    
    private fun createQuickReplyIntent(sessionId: String): Intent {
        return Intent().apply {
            putExtra("session_id", sessionId)
            putExtra("action", "quick_reply")
        }
    }
    
    private fun createPaymentResultIntent(paymentId: String, orderId: String): Intent {
        return Intent().apply {
            putExtra("payment_id", paymentId)
            putExtra("order_id", orderId)
            putExtra("action", "view_payment_result")
        }
    }
    
    private fun createPromotionIntent(promotionId: String): Intent {
        return Intent().apply {
            putExtra("promotion_id", promotionId)
            putExtra("action", "view_promotion")
        }
    }
    
    private fun createSystemNotificationIntent(notificationId: String): Intent {
        return Intent().apply {
            putExtra("notification_id", notificationId)
            putExtra("action", "view_system_notification")
        }
    }
    
    private fun createDefaultIntent(): Intent {
        return Intent().apply {
            putExtra("action", "open_main")
        }
    }
    
    private fun loadImageAndSetBigPicture(builder: NotificationCompat.Builder, imageUrl: String) {
        // 异步加载图片并设置大图样式
        // 这里应该使用图片加载库如Glide或Picasso
    }
    
    private fun uploadTokenToServer(userId: String, token: String) {
        // 上传FCM token到服务器
    }
    
    private fun saveNotificationRecord(remoteMessage: RemoteMessage) {
        // 保存通知记录到本地数据库
    }
}
